/**
 * 删除学生和教师通用接口
 * 
 * admin/user/del
 */

const User_info = require('../../../models/usersInfo')
const Users = require('../../../models/users')
const utils = require('../../../utils/index')
const MySQLManager = require('../../../utils/MySQLManager');
const sequelize = MySQLManager
const Sequelize = require('sequelize')
const Op = Sequelize.Op
const $ = require('../../../utils/common')

const del_students = async function (req, res) {
    try {
        // 传数组
        if (!req.query.id) {
            $.sendMessage(res, 1015, '参数id没有传')
            return
        }

        // 根据 id 找到user_name ， 用user_name 删除
        var user_names = await User_info.findAndCountAll({
            where: {
                id: {
                    [Op.or]:req.query.id.split(',') 
                }
            },
            attributes: ['user_name']
        })

        // 格式化user_name
        var user_names_array = user_names.rows.map(item => {
            return item.dataValues.user_name + ''
        })

        // 删除事务
        return sequelize.transaction(function (t) {
            return User_info.destroy(
            {
                where: {
                    user_name: {
                        [Op.or]: user_names_array
                    }
                }
            }
            , 
            {transaction: t}).then(function (user) {
            return Users.destroy(
                {
                    where: {
                        user_name: {
                            [Op.or]: user_names_array
                        }
                    }
                }
                , {transaction: t});
            })
        
        }).then(function (result) {
            res.json({
                code: 200,
                message: '删除成功',
                result: result
            })
            // 事务已被提交
            // result 是 promise 链返回到事务回调的结果

            // // 日志
            utils.create_a_log(req, '学生列表', '删除')
            return
            
        }).catch(function (err) {
            res.json({
                code: 1017,
                message: '删除失败',
                err: 'err' + err
            })
            // 事务已被回滚
            // err 是拒绝 promise 链返回到事务回调的错误
        });

    }
    catch(error) {
        $.sendMessage(res, 1015, 'error' + error)
        return
    }
    
}
    
module.exports = del_students